package com.sofwin.controller;

import com.sofwin.Constants;
import com.sofwin.dto.ResourceDto;
import com.sofwin.pojo.SysUser;
import com.sofwin.service.ResourceService;
import com.sofwin.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private ResourceService resourceService;

    @RequestMapping("toIndex")
    public String toIndex(HttpSession session, Model model){
        // 在session中保存有当前用户的信息  id roleId
        SysUser user = (SysUser)session.getAttribute(Constants.CURR_USER);
        // 根据roleId查询当前角色所拥有的权限 （集合）
       List<ResourceDto> resources = resourceService.selectRoleResource(user.getRoleId());
        // 集合放入到作用域中
        model.addAttribute("menus",resources);
        return "index";
    }

    @PostMapping("login")
    public String login(SysUser user, String code, HttpSession session){
        if(code==null){
            return "redirect:index.jsp";
        }
        // 取生成验证码时存放在session中的字符串
        String oldCode = session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY).toString();
        if(!code.equals(oldCode)){
            return "redirect:index.jsp";
        }
//        boolean status = userService.checkLogin(user);
//        if(status){
//            //查询用户新兵放入session
//            user = userService.selectUser(user);
//            session.setAttribute(Constants.CURR_USER,user);
//            return "redirect:toIndex";
//        }else{
//            return "redirect:index.jsp";
//        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getLoginAccount(),user.getLoginPwd());
        try {
            subject.login(token);
        }catch (UnknownAccountException ex){
            // 说明用户名不存在
            return "redirect:index.jsp";
        }catch (IncorrectCredentialsException ex){
            return "redirect:index.jsp";
        }
        //查询用户新兵放入session
            user = userService.selectUser(user);
            session.setAttribute(Constants.CURR_USER,user);
            return "redirect:toIndex";
    }

    @RequestMapping("logout")
    public String logout(HttpSession session){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        session.removeAttribute(Constants.CURR_USER);
        return "redirect:index.jsp";
    }
}
